<template>
  <div class="width-100">
    <draggable v-model="dragList" @end="onEnd"  handle=".drag-mover">
      <transition-group>
        <div v-for="(action, index) in dragList" :key="index" class="mar-btm">
          <div class="flex-com mar-btm">
            <span class="label-title font-weight-bold drag-mover">行为{{index + 1}}</span>
            <el-select
              v-model="action.reType" placeholder="请选择动作"
              size="mini" class="width-input"
              @change="(value) => changeAction(value, action)">
              <el-option-group v-for="group in eventType" :key="group.label" :label="group.label">
                <el-option v-for="item in group.options" :key="item.reType" :label="item.name" :value="item.reType">
                </el-option>
              </el-option-group>
            </el-select>
            <span class="el-icon-copy-document cursor-pointer font-hover-primary" @click="copyAction(index)"></span>
            <span class="el-icon-delete cursor-pointer font-hover-danger" @click="deleteAction(index)"></span>
            <el-tooltip effect="dark" content="跨事件复制" placement="top">
              <span class="el-icon-document-copy cursor-pointer " @click="copyStoreAction(index)"></span>
            </el-tooltip>
          </div>
          <!--各种行为事件-->
          <EventComponent v-show="action.reType" :action="action" :widget="widget" :iftttLogic="iftttLogic">
            <template slot="selectAction" v-if="action.reType==='userNoAction'">
              <div class="flex-com mar-btm">
                <span class="label-title font-weight-bold iconfont icon-branch"></span>
                <el-select
                  v-model="action.value.action.reType" placeholder="请选择动作"
                  size="mini" class="width-input"
                  @change="(value) => changeAction(value, action.value.action)">
                  <el-option-group v-for="group in eventType" :key="group.label" :label="group.label">
                    <el-option v-for="item in group.options" :key="item.reType" :label="item.name" :value="item.reType">
                    </el-option>
                  </el-option-group>
                </el-select>
              </div>
              <div class="flex-com">
                <EventComponent v-show="action.value.action.reType" :action="action.value.action" :widget="widget" :iftttLogic="iftttLogic"></EventComponent>
              </div>
            </template>
          </EventComponent>
          <!--延迟时间-->
          <div class="flex-com mar-btm">
            <span class="label-title">延迟</span>
            <el-input-number
              v-model="action.delay" :step="100" :min="0"
              size="mini" class="width-input"></el-input-number>
            <span>ms</span>
          </div>
          <el-divider></el-divider>
        </div>
      </transition-group>
    </draggable>
    <div class="font-color-primary font-size-12 font-weight-bold ">
      <div class="display-inline cursor-pointer mar-rgt-20" @click="addAction(relAction)">
        <i class="iconfont icon-tianjia"></i><span class="mar-lft-5">添加行为</span>
      </div>
      <div class="display-inline cursor-pointer" @click="pasteAction(relAction)">
        <i class="el-icon-document-copy"></i><span class="mar-lft-5">粘贴行为</span>
      </div>
    </div>
  </div>
</template>

<script>
  import SelectVariable from "./SelectVariable.vue";
  import {dataTypeArray, commonConfig} from "@/config/common";
  import CodeEditor from '@/components/IDE/CodeEditor';
  import {dftPadCode} from '@/config/string';
  import {formatJsCode, generateUID, messageHandle} from '@/utils';
  import {confirmHandle, deepCopy} from "@/utils";
  import {mapActions, mapState} from "vuex";
  import {getAtomicAttr} from "@/utils";
  import IftttFiled from "./IftttFiled.vue";
  import IftttState from "./IftttState.vue";
  import EventComponent from "./EventComponent.vue";
  import draggable from 'vuedraggable';
  import {getStorage, setStorage, StorageKey} from "@/config/sessions";
  import InputsComponent from './InputsComponent.vue'

  export default {
    name: 'ActionComponent',
    props: {
      widget: {
        type: Object,
        default: () => {
          return {};
        }
      },
      relAction: {
        type: Array,
        default: () => {
          return [];
        },
      },
      iftttLogic: {
        type: Boolean,
        default: () => {
          return false;
        },
      },
    },
    components: {
      SelectVariable, CodeEditor, IftttFiled, IftttState, draggable, InputsComponent,EventComponent
    },
    data() {
      return {
        dataTypeArray: dataTypeArray,
        commonConfig: commonConfig,
        eventType: [
          {
            label: "基础动作",
            options: [
              {name: "跳转页面", type: "pageCtl", reType: 'pageCtl'},
              {name: "修改组件", type: "editVar", reType: 'editVar'},
              {name: "多状态处理", type: "iftttLogicList", reType: 'iftttLogicList'},
              {name: "控制设备", type: "deviceCtl", reType: 'deviceCtl'},
              {name: "逻辑处理", type: "logicCmd", reType: 'logicCmd'},
              {name: "修改全局变量", type: "editVar", reType: 'editGlobalVar'},
              {name: "组合命令", type: "sceneCtl", reType: 'sceneCtl'},
              {name: "结束组合命令", type: "stopScene", reType: 'stopScene'},
              {name: "关联事件", type: "relatedAction", reType: 'relatedAction'},
              {name: "情景查询", type: "sceneQuery", reType: 'sceneQuery'},
              {name: "房间属性设置", type: "setRoomAttribute", reType: 'setRoomAttribute'},
              {name: "网络数据发送", type: "netDataSend", reType: 'netDataSend'},
            ],
          },
          {
            label: "其他动作",
            options: [
              {name: "字符插入", type: "logicStringInsert", reType: 'logicStringInsert'},
              {name: "字符删除", type: "logicStringDelete", reType: 'logicStringDelete'},
              {name: "状态处理", type: "iftttLogic", reType: 'iftttLogic'},
              {name: "内置功能", type: "padDefaultCmd", reType: 'padDefaultCmd'},
              {name: "释放会议", type: "concludeMeeting", reType: 'concludeMeeting'},
              {name: "用户无操作", type: "userNoAction", reType: 'userNoAction'},
              {name: "显示提示信息", type: "showToast", reType: 'showToast'},
              // { name: "打印日志", type: "print", reType: 'print' },
            ],
          },
        ],
        //控制设备
        deviceCtl: {
          currentDevice: {}, //当前选中设备
          customDevice: {}, //当前自定义命令
        },
        getAtomicAttr: getAtomicAttr,
        stateListAction: [],
        dragList: [],
      };
    },
    watch: {
      relAction: {
        handler(val) {
          this.dragList = val;
        },
        deep: true,
        immediate: true
      },
    },
    computed: {
      ...mapState({
	      curPageHandler: state => state.ide.curPageHandler,
      }),
    },
    methods: {
      onEnd() {
        this.$emit('dragEvent', this.dragList);
      },
      // 添加行为
      addAction(event) {
        if (event.length > 0 && !this.objectArtIsEmpty(event)) {
          this.$notify({
            message: '请填写完整行为',
            type: 'error',
            duration: 3000,
          });
          return false;
        }
        event.push({
          name: "",
          key: null,
          type: "",
          reType: '',
          delay: 0,
          value: {},
        });
      },
      // 修改行为
      changeAction(val, action) {
        action.portsType = '';
        this.eventType.forEach(item => {
          item.options.forEach(option => {
            if (option.reType === val) {
              action.type = option.type;
              action.name = option.name;
            }
          });
        });
        switch (val) {
          case "logicStringInsert":
            this.changeActionList(action);
            action.value = {
              'text': {
                value: "",
                type: "",
                name: "关联文本",
              },
              'index': {
                value: "",
                type: "relatedAtomic",
                name: "字符插入位置",
              },
              'character': {
                value: "",
                type: "",
                name: "插入的字符",
              }
            };
            break;
          case "logicStringDelete":
            this.changeActionList(action);
            action.value = {
              'text': {
                value: "",
                type: "",
                name: "关联文本",
              },
              'index': {
                value: "",
                type: "relatedAtomic",
                name: "字符插入位置",
              },
            };
            break;
          case "netDataSend":
            this.changeActionList(action);
            action.value = {
              "type": "udp",
              'ip': {
                value: "",
                type: "string",
                name: "ip地址",
              },
              'port': {
                value: "",
                type: "string",
                name: "端口号",
              },
              'data': {
                value: "",
                type: "string",
                name: "数据",
              },
            };
            break;
          case "iftttLogicList":
            this.changeActionList(action);
            action.value = {
              'actions': []
            };
            break;
          case "setRoomAttribute":
            this.changeActionList(action);
            action.value = {
              'key': {
                value: "",
                type: "string",
              },
              'value': {
                value: "",
                type: "string",
              },
            };
            break;
          case "userNoAction":
            this.changeActionList(action);
            action.value = {
              'time': {
                value: 1,
                type: "int",
                name: "延迟时间",
              },
              'action': {
                value: "",
                reType: "",
                name: "触发动作",
              },
            };
            break;
          case "showToast":
            this.changeActionList(action);
            action.value = {
              'time': {
                value: 3000,
                type: "int",
                name: "显示时间",
              },
              'text': {
                value: "请稍后再试!",
                name: "显示的文本",
                type: "string",
              },
            };
            break;
          case "concludeMeeting":
            this.changeActionList(action);
            action.value = {
              'meetingId': {
                value: "",
                type: "string",
                name: "会议id",
              },
            };
            break;
          default:
            this.changeActionList(action);
            break;
        }
      },
      // 简化
      changeActionList(action) {
        action.value = {};
        action.key = null;
        action.currentParams && delete action.currentParams;
        action.atomic && delete action.atomic;
        action.command && delete action.command;
        action.autoType && delete action.autoType;
        action.state && delete action.state;
        action.toAtomic && delete action.toAtomic;
        action.logicStringInsert && delete action.logicStringInsert;
      },
      // 删除行为
      deleteAction(index) {
        confirmHandle({label: `确定要删除行为${index + 1}吗?`}).then(() => {
          this.relAction.splice(index, 1);
          messageHandle({type: 'success', msg: '行为删除成功！'});
        }).catch(() => {
        });
      },
      // 复制行为
      copyAction(index) {
        const callback = this.relAction[index];
        if (!callback) return;
        //复制控制设备行为加一个字段，选设备时不清除参数
        if (callback.reType === 'deviceCtl') {
          callback.isCopy = true
        }
        this.relAction.splice(index, 0, deepCopy(callback));
        setStorage(StorageKey.copiedActions, callback);
      },
      copyStoreAction(index) {
        const callback = this.relAction[index];
        if (!callback) return;
        //复制控制设备行为加一个字段，选设备时不清除参数
        if (callback.reType === 'deviceCtl') {
          callback.isCopy = true
        }
        setStorage(StorageKey.copiedActions, callback);
        this.$notify({
          message: '复制成功',
          type: 'success',
          duration: 2000,
        });
      },

      //判断对象是否完整
      objectArtIsEmpty(data) {
        let result;
        data.forEach((item) => {
          switch (item.reType) {
            case 'pageCtl':
            case 'editGlobalVar':
            case 'sceneCtl':
            case 'stopScene':
            case 'sceneQuery':
            case 'editVar':
            case 'relatedAction':
            case 'padDefaultCmd':
            case 'logicCmd':
              result = JSON.stringify(item.value) !== '{}' && item.value.value !== '';
              break;
            //设备控制
            case 'deviceCtl':
              if (JSON.stringify(item.value) !== '{}') {
                if (item.value.method === 'sendOriginData') {
                  //自定义码流
                  result = true;
                } else if (item.currentParams.length === 0) {
                  //无参数
                  result = item.value.method !== '';
                } else if (item.currentParams.length > 0) {
                  //有参数
                  if (JSON.stringify(item.value.params) !== '{}') {
                    for (let key in item.value.params) {
                      result = item.value.params[key].value !== '' && item.value.params[key].value !== undefined;
                    }
                  } else {
                    result = false;
                  }
                }
              }
              break;
            //字符串插入
            case 'logicStringInsert':
              result = item.value.text.value !== '' && item.value.character.value !== '';
              break;
            //字符串删除
            case 'logicStringDelete':
              result = item.value.text.value !== '';
              break;
            case 'netDataSend':
              result = item.value.ip.value !== '' && item.value.port.value !== '' && item.value.data.value !== '';
              break;
            case 'iftttLogic':
            case 'iftttLogicList':
              result = JSON.stringify(item.value) !== '{}';
              break;
            case 'setRoomAttribute':
              result = item.value.key.value !== '' && item.value.value.value !== '';
              break;
            case 'userNoAction':
              result = item.value.action.value !== '';
              break;
            case 'showToast':
              result = item.value.time.value !== '' && item.value.text.value !== '' ;
              break;
            case 'concludeMeeting':
              result = item.value.meetingId.value !== '' && item.value.meetingId.value !== '' ;
              break;
            default:
              result = false;
              break;
          }
        })
        return result
      },
      verify() {
        const lastValue = this.stateListAction[this.stateListAction.length - 1];
        const conditions = lastValue ? lastValue.value.conditions : [];
        const lastConditions = conditions[conditions.length - 1];
        if (lastValue !== undefined && lastConditions !== undefined && lastConditions.value2.value.length === 0 && lastConditions.value2.autoType !== 4) {
          //判断条件属性必须 判断上一条内容为空 ，类型不是空值类型
          this.$notify({
            message: '请填写完整的判断条件！',
            type: 'warning',
            duration: 3000,
          });
          return false;
        } else if (lastValue !== undefined && lastValue.value.actions.length === 0 && lastValue.value.elseActions.length === 0) {
          //满足和不满足条件必须其中一个
          this.$notify({
            message: '请至少填写一项条件满足或不满足后触发的操作！',
            type: 'warning',
            duration: 3000,
          });
          return false;
        } else {
          return true;
        }
      },
      pasteAction(event) {
        const copiedActions = getStorage(StorageKey.copiedActions, true) || {};
        console.log(123, copiedActions)
        event.push(copiedActions)
      }
    },
  }
</script>
<style lang="less" scoped>
  /**子组件分别继承不同父组件的样式 */
  .drag-mover {
    cursor: move;
  }

  .divider {
    height: 8px;
    background: @colorGray96;
    margin-left: -15px;
    margin-right: -15px;
  }

  .event-dock-container {
    height: calc(100vh - 90px);
    overflow: auto;

    .pad-divider {
      padding: 20px 10px;
      box-sizing: border-box;
      border-bottom: 1px solid #dadce5;
    }

    .title {
      margin: 0;
      color: @colorGray10;
      font-size: 14px;
    }

    .flex-com {
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .wrap {
      flex-wrap: wrap;
      gap: 2px;
    }


    .label-title {
      min-width: 42px;
      color: #12131A;
      font-size: 14px;
      text-align: center;
    }


    .width-input {
      width: 100%;

      /deep/ .el-input__inner {
        background: #f7f8fa;
      }
    }

  }

  .ifttt-cont {
    width: 100%;

    .flex-com {
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .label-title {
      min-width: 42px;
      color: @colorGray10;
      font-size: 14px;
      text-align: center;
      flex-shrink: 0;
    }

    .width-input {
      width: 350px;

      /deep/ .el-input__inner {
        width: 100%;
        background: #fff;
      }
    }

    &::-webkit-scrollbar {
      display: none;
    }

  }

  /deep/ .el-collapse-item__content {
    padding-bottom: 10px;
  }

  /deep/ .el-collapse-item__wrap {
    border-bottom: 10px solid #EBEEF5;
  }

  .header-icon {
    color: #e0572d;
  }
</style>
